package cn.java81.jdbc;

import cn.java81.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author oldliu
 * @since 1.0
 */
public class TransactionTest {
    public static void main(String[] args) {
        doZhuanZhang("laozhang","laoma",300);
    }
    public  static void doZhuanZhang(String from,String to,double money){
        String sql="update bank set balance=balance-? where acno=?";
        String sql2="update bank set balance=balance+? where acno=?";
        Connection con= DbUtil.getConnection();
        PreparedStatement ps=null;
        try {
            //关闭自动提交
            con.setAutoCommit(false);
            ps=con.prepareStatement(sql);
            ps.setDouble(1,money);
            ps.setString(2,from);
            int r1=ps.executeUpdate();
            DbUtil.close(ps);
            ps=con.prepareStatement(sql2);
            ps.setDouble(1,money);
            ps.setString(2,to);
            int r2=ps.executeUpdate();
            if(r1>0&r2>0){
                con.commit();
            }else{
                con.rollback();
            }
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            DbUtil.close(null,ps,con);
        }
    }
}
